import time, math, json
from django.shortcuts import render         
from django.db.models import Q
from microerp.apps.customer.forms import CustomerForm
from microerp.apps.customer.models import Customer
from microerp.apps.base.models import *
from microerp.apps.base.views import *

 
#add one new customer
def add_customer(request):
	if islogin(request):
        #name = request.POST.get('account_name')
		if request.method=='POST':
			form = CustomerForm(request.POST)
			if form.is_valid():
				user_id = get_user_id(request)
				#将form中的ModelForm转化成Model(来自Stackoverflow)
				cust = form.save(commit=False)
				cust.user = Users.objects.filter(id=user_id)[0]
				cust.created_date = time.strftime("%Y-%m-%d", time.localtime())
				cust.save()
				return render(request, 'customer/new-cust.html',{'sign':True,'form':form})
			else:
				return render(request, 'customer/new-cust.html',{'form':form,'error':True})
		else:
		    return render(request,'customer/new-cust.html', {'form':CustomerForm()})
	else:
		return render(request, 'base/signin.html')

#获取客户列表
def cust_list(request):
	if islogin(request):
		user = Users.objects.filter(id=get_user_id(request))[0]
		#query-----查询关键字
		#page------页码（每页10条数据）
		query = request.GET.get('query')
		page = request.GET.get('page',1)
		#得到顾客列表数据
		cust_list,totalRecords = get_cust(query,user,int(page))
		#开始获得分页数据
		totalPage = math.ceil(totalRecords / 10)

		return render(request, 'customer/cust-list.html',{"list":cust_list,"query":query,"totalPage":totalPage,"totalRecords":totalRecords})
	else:
		return render(request, 'base/signin.html')

#查询客户列表数据的方法
def get_cust(obj,user,page):
	cust_list = []     #新建一个list存储客户列表
	totalRecords = 0   #总记录数量
	if obj:
		cust_list = Customer.objects.filter(user=user).filter(
            Q(account_name__icontains=str(obj)) |
            Q(qq_nickname__icontains=str(obj)) | 
            Q(weixin_nickname=str(obj))      |
            Q(qq=str(obj))      |
            Q(weixin=str(obj))      
            ).order_by("id")[(page - 1) * 10:page * 10 - 1]
		totalRecords = Customer.objects.filter(user=user).filter(
            Q(account_name__icontains=str(obj)) |
            Q(qq_nickname__icontains=str(obj)) | 
            Q(weixin_nickname=str(obj))      |
            Q(qq=str(obj))      |
            Q(weixin=str(obj))  
            ).count()
	else:
		cust_list = Customer.objects.filter(user=user).order_by("id")[(page - 1) * 10:page * 10 - 1]
		totalRecords = Customer.objects.filter(user=user).count()
	return cust_list,totalRecords

#客户详细信息
def cust_info(request):
	if islogin(request):
		user = Users.objects.filter(id=get_user_id(request))[0]
		if request.method == 'GET':
			id = request.GET.get('cust_id')
			cust = Customer.objects.filter(user=user).filter(id=id)[0]
			if cust:
				return render(request, 'customer/cust-info.html',{'cust':cust})
			else:
				return render(request,'customer/cust-info.html')
	else:
		return render(request, 'customer/signin.html')

#获取所有客户数据(name)
def api_get_custs(request):
	if(islogin(request)):
		user = Users.objects.filter(id=get_user_id(request))[0]
		customers = Customer.objects.filter(user=user)
		customers_dict = [cust.name_dict() for cust in customers]
		return HttpResponse(json.dumps(customers_dict), content_type="application/json")
	else:
		return render(request, 'base/signin.html')